package org.daoImpl;

import org.dao.FloorDao;
import org.model.*;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tedzy on 2015/5/14.
 * Floor Dao Impl
 */
public class FloorDaoImpl extends HibernateDaoSupport implements FloorDao {
    @Override
    public int newFloor(int threadId, int uid, String content) {
        Floor fl = new Floor();
        fl.setAuthor(uid);
        fl.setThreadId(threadId);
        fl.setContent(content);
        this.getHibernateTemplate().save(fl);
        return fl.getId();
    }

    @Override
    public int newInFloor(int floorId, int uid, String content) {
        Floor fl = new Floor();
        fl.setAuthor(uid);
        fl.setThreadId(floorId);
        fl.setContent(content);
        fl.setIsInfloor(1);
        this.getHibernateTemplate().save(fl);
        return fl.getId();
    }

    @Override
    public boolean addInFloor(int parentFloor, int inFloor) {
        org.model.Floor t;
        List list = this.getHibernateTemplate().find("from Floor where id=?", parentFloor);
        if(list.size() >= 1){
            t = (Floor)list.get(0);
        }else{
            return false;
        }

        String newFloorStr = t.getInfloorId();
        if(newFloorStr==null||newFloorStr.equals("")){
            t.setInfloorId("" + inFloor);
        }else {
            t.setInfloorId(newFloorStr + "," + inFloor);
        }
        this.getHibernateTemplate().update(t);
        return true;
    }

    @Override
    public List<Floor> readFloors(String floorsCsv) {
        List list = this.getHibernateTemplate().find("from Floor where id in(" + floorsCsv + ")");
        List<Floor> floors = new ArrayList<>();
        for(Object floor : list){
            floors.add((Floor) floor);
        }
        return floors;
    }

    @Override
    public int incZan(int floorId) {
        Floor floor;
        List list = this.getHibernateTemplate().find("from Floor where id=?", floorId);
        if(list.size() <= 0){
            return -1;
        }else{
            floor = (Floor) list.get(0);
            floor.setZan(floor.getZan() + 1);
            this.getHibernateTemplate().update(floor);
            return floor.getZan();
        }
    }
}
